package org.brownflat.lighthouse.web;


import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Log4jConfigurator {
    private static final Logger LOG = Logger.getLogger(Log4jConfigurator.class);
    private String fullPath = null;
    private String defaultPath = null;

    public Log4jConfigurator(String path, String pattern, String def) {
        InetAddress localMachine;
        String hostname = null;
        try {
            localMachine = InetAddress.getLocalHost();
            hostname = localMachine.getHostName();
            fullPath = path + String.format(pattern, hostname);
            defaultPath = path + def;
        } catch (UnknownHostException e) {
            LOG.error(e);
        }
        init();
    }

    private void init() {
        InputStream stream = this.getClass().getResourceAsStream(fullPath);
        LOG.info(String.format("Attempting to find logging configuration at [%s]", fullPath));

        if (stream == null) {
            stream = this.getClass().getResourceAsStream(defaultPath);
            LOG.info(String.format("Attempting to find logging configuration at [%s]", defaultPath));
        }
        DOMConfigurator configurator = new DOMConfigurator();
        configurator.doConfigure(stream, LogManager.getLoggerRepository());
        LOG.info("Logging configured.");
    }
}